<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>运输订单统计</title>
    <!-- 引入WeUI CSS -->
    <link rel="stylesheet" href="./weui/weui.min.css">
    <style>
        /* 全局样式 */
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            min-height: 100vh;
            padding: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .page-container {
            max-width: 800px;
            width: 100%;
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }
        
        /* 头部样式优化 */
        .header {
            text-align: center;
            padding: 15px 0 10px;
            background: linear-gradient(to right, #07C160, #10a5c5);
            color: white;
            position: relative;
        }
        
        .header-title {
            font-size: 20px;
            font-weight: 600;
            margin: 0;
        }
        
        /* 统计卡片样式 */
        .stats-container {
            display: flex;
            flex-wrap: wrap;
            padding: 15px;
            gap: 10px;
        }
        
        .stat-card {
            flex: 1;
            background: white;
            padding: 12px;
            border-radius: 10px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
            text-align: center;
            min-width: 120px;
            border-left: 4px solid #acd9c2;
        }
        
        .stat-card.poor {
            border-left-color: #ff6b6b;
        }
        
        .stat-title {
            font-size: 13px;
            color: #666;
            margin-bottom: 5px;
        }
        
        .stat-value {
            font-size: 22px;
            font-weight: bold;
            color: #333;
            margin: 5px 0;
        }
        
        .stat-desc {
            font-size: 11px;
            color: #999;
        }
        
        /* 日期范围信息 */
        .date-range-info {
            text-align: center;
            padding: 8px 15px;
            color: #666;
            font-size: 13px;
            background-color: #f8f9fa;
            border-top: 1px solid #eee;
            border-bottom: 1px solid #eee;
        }
        
        /* 筛选区域样式 */
        .filter-container {
            padding: 15px;
        }
        
        .filter-row {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }
        
        .filter-group {
            flex: 1;
        }
        
        .filter-label {
            font-size: 14px;
            color: #333;
            margin-bottom: 5px;
            display: block;
            font-weight: 500;
        }
        
        .filter-input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            box-sizing: border-box;
        }
        
        .filter-input:focus {
            border-color: #07C160;
            outline: none;
        }
        
        .button-row {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        
        .btn {
            flex: 1;
            padding: 10px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .btn-primary {
            background: linear-gradient(to right, #07C160, #10a5c5);
            color: white;
            box-shadow: 0 2px 5px rgba(7, 193, 96, 0.3);
        }
        
        .btn-default {
            background: #f5f5f5;
            color: #333;
        }
        
        .btn:active {
            transform: translateY(1px);
        }
        
        /* 响应式调整 */
        @media (max-width: 480px) {
            body {
                padding: 5px;
            }
            
            .page-container {
                border-radius: 12px;
            }
            
            .stat-card {
                /* min-width: calc(50% - 10px); */
            }
            
            .filter-row {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="page-container">
         <!-- <div id="loading">授权检查中...</div> -->
        <div class="header">
            <h1 class="header-title">运输订单统计</h1>
        </div>
        
        <div class="stats-container">
            <div class="stat-card">
                <div class="stat-title">订单数量</div>
                <div class="stat-value" id="orderCount">0</div>
                <div class="stat-desc">总计</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">起点重量 (kg)</div>
                <div class="stat-value" id="startWeight">0</div>
                <div class="stat-desc">总计</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">终点重量 (kg)</div>
                <div class="stat-value" id="endWeight">0</div>
                <div class="stat-desc">总计</div>
            </div>
            <div class="stat-card poor">
                <div class="stat-title">重量差异 (kg)</div>
                <div class="stat-value" id="weightDiff">0</div>
                <div class="stat-desc">总计</div>
            </div>
        </div>
        
        <div class="date-range-info" id="dateRangeInfo"></div>
        
        <div class="filter-container">
            <div class="filter-row">
                <div class="filter-group">
                    <label class="filter-label">开始时间</label>
                    <input class="filter-input" type="datetime-local" id="startDate">
                </div>
                <div class="filter-group">
                    <label class="filter-label">结束时间</label>
                    <input class="filter-input" type="datetime-local" id="endDate">
                </div>
            </div>
            
            <div class="filter-row">
                <div class="filter-group">
                    <label class="filter-label">起点公司</label>
                    <input class="filter-input" type="text" id="startCompany" placeholder="输入起点公司名">
                </div>
                <div class="filter-group">
                    <label class="filter-label">终点公司</label>
                    <input class="filter-input" type="text" id="endCompany" placeholder="输入终点公司名">
                </div>
            </div>
            
            <div class="button-row">
                <button type="button" class="btn btn-default" onclick="resetFilters()">清空筛选</button>
                <button type="button" class="btn btn-primary" onclick="filterStats()">筛选统计</button>
            </div>
        </div>
    </div>

    <!-- 引入WeUI JS -->
    <script src="./weui/weui.min.js"></script>
    <script src="./weui/axios.min.js"></script>
    <script src="./axios.js"></script>
     <script src="./wechat-auth.js"></script>
    <script src="./api.js"></script>
    <script>
        // 设置默认日期为当月1号到当前日期时间
        function setDefaultDate() {
            const today = new Date();
            const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
            
            const formatDateTime = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                return `${year}-${month}-${day}T${hours}:${minutes}`;
            };
            
            document.getElementById('startDate').value = formatDateTime(firstDay);
            document.getElementById('endDate').value = formatDateTime(today);
            
            updateDateRangeInfo(firstDay, today);
        }
        
        // 更新日期范围信息显示
        function updateDateRangeInfo(startDate, endDate) {
            const options = { 
                year: 'numeric', 
                month: 'short', 
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            };
            const startStr = startDate.toLocaleDateString('zh-CN', options);
            const endStr = endDate.toLocaleDateString('zh-CN', options);
            
            const dateRangeElement = document.getElementById('dateRangeInfo');
            if (dateRangeElement) {
                dateRangeElement.textContent = `统计时间: ${startStr} 至 ${endStr}`;
            }
        }
        
        // 将日期时间转换为时间戳
        function dateToTimestamp(dateString) {
            if (!dateString) return null;
            return Math.floor(new Date(dateString).getTime() / 1000);
        }
        
        // 更新统计显示
        function updateStatsDisplay(stats) {
            const orderCountElement = document.getElementById('orderCount');
            const startWeightElement = document.getElementById('startWeight');
            const endWeightElement = document.getElementById('endWeight');
            const weightDiffElement = document.getElementById('weightDiff');
            
            if (orderCountElement) {
                orderCountElement.textContent = stats.num || 0;
            }
            
            if (startWeightElement) {
                startWeightElement.textContent = stats.heavy ? parseFloat(stats.heavy).toFixed(2) : '0';
            }
            
            if (endWeightElement) {
                endWeightElement.textContent = stats.heavy_end ? parseFloat(stats.heavy_end).toFixed(2) : '0';
            }
            
            if (weightDiffElement) {
                weightDiffElement.textContent = stats.poor ? parseFloat(stats.poor).toFixed(2) : '0';
            }
        }
        
        // 筛选统计
        function filterStats() {
            const startDate = document.getElementById('startDate')?.value;
            const endDate = document.getElementById('endDate')?.value;
            const startCompany = document.getElementById('startCompany')?.value;
            const endCompany = document.getElementById('endCompany')?.value;
            
            // 显示加载中
            const loading = weui.loading('加载中...');

            // 准备API参数
            let params = {
                stime: dateToTimestamp(startDate),
                etime: dateToTimestamp(endDate),
                company: startCompany || '',
                end_company: endCompany || '',
                 openid:localStorage.getItem('wechat_openid')
            };
            
            
            // 调用API获取统计数据
            orderStatistics(params).then(response => {
                // 正确处理响应数据
                let stats;
                if (response && response.data) {
                    // 如果返回的是 { data: { ... } } 格式
                    stats = response.data.data || response.data;
                } else {
                    stats = response;
                }
                
                console.log('获取到的统计数据:', stats);
                
                updateStatsDisplay(stats);
                loading.hide();
                
                // 更新日期范围显示
                if (startDate && endDate) {
                    updateDateRangeInfo(new Date(startDate), new Date(endDate));
                }
                
            }).catch(error => {
                console.error('获取统计数据失败:', error);
                loading.hide();
                weui.toast('加载失败', {
                    className: 'weui-toast_warn',
                    duration: 2000
                });
            });
        }
        
        // 重置筛选条件
        function resetFilters() {
            setDefaultDate();
            const startCompanyElement = document.getElementById('startCompany');
            const endCompanyElement = document.getElementById('endCompany');
            
            if (startCompanyElement) {
                startCompanyElement.value = '';
            }
            
            if (endCompanyElement) {
                endCompanyElement.value = '';
            }
            
            filterStats();
        }
        
        // 初始化页面
        async function initPage() {
            setDefaultDate();
            // 显示加载中
            const loading = weui.loading('加载数据...');
            
            try {
                let endDate = document.getElementById('endDate').value;
                let startDate = document.getElementById('startDate').value;
                  console.log('初始化参数:',startDate, endDate);
                // 准备API参数
                let params = {
                    stime: dateToTimestamp(startDate),
                    etime: dateToTimestamp(endDate),
                    company: '',
                    end_company: '',
                    openid:localStorage.getItem('wechat_openid')
                };
              
                
                let response = await orderStatistics(params);
                
                // 正确处理响应数据
                let stats;
                if (response && response.data) {
                    stats = response.data.data || response.data;
                } else {
                    stats = response;
                }
                
                console.log('初始化统计数据:', stats);
                
                updateStatsDisplay(stats);
                loading.hide();
                
            } catch (error) {
                console.error('获取统计数据失败:', error);
                loading.hide();
                weui.toast('加载失败', {
                    className: 'weui-toast_warn',
                    duration: 2000
                });
            }
        }
        
        document.addEventListener('DOMContentLoaded',async function() {
                 try {
                // 检查授权
                // const isAuthed = await weChatAuth.checkAuth();
                
                // if (isAuthed) {
                //    this.init()
                 initPage()
                // } else {
                    // 授权中，等待跳转
                    // document.getElementById('loading').innerHTML = '微信授权中...';
                // }
            } catch (error) {
                console.error('页面初始化失败:', error);
                document.getElementById('loading').innerHTML = '加载失败，请刷新页面';
            }
         
        } );
        
        // 暴露函数给全局作用域
        window.filterStats = filterStats;
        window.resetFilters = resetFilters;
    </script>
</body>
</html>